import 'package:dio/dio.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/pages/models/http_response/http_response_model.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../custom_exception/api_exception.dart';

// 文件相关的API扩展
extension ApiHelperFileExtension on ApiHelper {
  // MARK: - 申请阿里云OSS上传STS
  Future<Map<String, dynamic>> applySTS() {
    return httpManager
        .request<HttpResponseModel>(
      RequestType.GET,
      "/v1/file/oss/sts",
      HttpResponseModel.fromJson,
      queryParameters: null,
    )
        .then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.originData;
    });
  }

  // MARK: - OSS文件上传-预检查
  Future<Map<String, dynamic>> uploadPreCheck(
    String type,
    String fileName,
    String fileSize,
  ) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v1/file/upload/pre-check",
      HttpResponseModel.fromJson,
      queryParameters: {
        "type": type,
        "name": fileName,
        "size": fileSize,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.originData;
    });
  }

  // MARK: - 文件下载
  Future<bool> downloadFile(
    String url,
    String savePath, {
    ProgressCallback? onReceiveProgress,
  }) {
    return httpManager
        .downloadFile<HttpResponseModel>(
            url, savePath, HttpResponseModel.fromJson,
            onReceiveProgress: onReceiveProgress)
        .then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }
}
